package com.zhuzg.oauth2.service;

import com.zhuzg.oauth2.domain.MyGrantedAuthority;
import com.zhuzg.oauth2.domain.MyUserDetail;
import com.zhuzg.oauth2.domain.SysUser;
import com.zhuzg.oauth2.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userMapper.findByUserName(username);
     /*   if(sysUser==null || sysUser.getStatus()==0){
          throw  new RuntimeException("用户不存在或者已经被禁用----");
        }*/
        // 类型转换 sysUser ===》 UserDetails
        MyUserDetail userDetail = new MyUserDetail();
        userDetail.setUsername(sysUser.getUsername());
        userDetail.setPassword(sysUser.getPassword());
        userDetail.setId(sysUser.getId()+"");
        userDetail.setEnable(true);
        userDetail.setMobile(sysUser.getMobile());
        userDetail.setEmail(sysUser.getEmail());

        //
        List<MyGrantedAuthority> grantedAuthorities = userMapper.findAuthritiesByUid(sysUser.getId());
        userDetail.setAuthorities(grantedAuthorities);

        return userDetail;
    }

    public UserDetails loadUserByMobile(String mobile) {

        SysUser sysUser = userMapper.findByMobile(mobile);
        if(sysUser==null || sysUser.getStatus()==0){
            throw  new RuntimeException("用户不存在或者已经被禁用=====");
        }
        // 类型转换 sysUser ===》 UserDetails
        MyUserDetail userDetail = new MyUserDetail();
        userDetail.setUsername(sysUser.getUsername());
        userDetail.setPassword(sysUser.getPassword());
        userDetail.setId(sysUser.getId()+"");
        userDetail.setEnable(true);
        userDetail.setMobile(sysUser.getMobile());
        userDetail.setEmail(sysUser.getEmail());

        //
        List<MyGrantedAuthority> grantedAuthorities = userMapper.findAuthritiesByUid(sysUser.getId());
        userDetail.setAuthorities(grantedAuthorities);

        return userDetail;

    }
}
